package com.malbbmsomanager.transactions;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import com.malbbmsomanager.R;
import com.malbbmsomanager.adapter.DM_BBM_List_Adapters;
import com.malbbmsomanager.caladapter.DM_BBM_CalculatorBrain;
import com.malbbmsomanager.caladapter.DM_BBM_CusListener;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class DM_BBM_InvoiceSalesEditOrderDetails extends Activity {

	private static final String TAG = null;
	// private PBDatabaseAdapter dbHelper;
	private String DBNAME = "dminvoicemanagerbbm.db";
	private SQLiteDatabase mydb;
	private String FORDHED_TABLE = "FOrdHed";
	private String FORDDET_TABLE = "FOrdDet";
	private String FORDTAXDT_TABLE = "FOrdTaxDt";
	private String FORDTAXRG_TABLE = "FOrdTaxRg";
	// Remote database adapter connection
	private DM_BBM_List_Adapters dbHelperCustomerItems;
	private SimpleCursorAdapter dataAdapterCusomerItems;
	String TaxChangeTaxCode, TaxChangeItemCode;
	// Read only components
	Button etbbmbbmproductcode, etbbmtaxcombination, btndeletetransaction,
			btnprinttransaction, btnundotransaction;
	EditText etbbmbbmcases, etbbmbbmproductname, etbbmbbmpacking, etbbmbrand,
			etbbmfinalqty, etbbmbbmdiscount, etbbmvalue, etbbmsalesprice,
			etbbmbrandcode, etbbmbbmdiscountamount, etbbmtaxamount,
			etbbmamountwouttax, etbbmbbmpacksize, etbbmquantity, etbbmfreeqty,
			etbbmtaxvalue, etbbmamountwithtax, myFilterCustomerItems;
	LinearLayout bbminvoiceitemslist, bbmsalesorditemdetail;
	String bbmItemCode, bbmItemName, DebtorTaxRegNo;
	String MainItemCode, PackSize, MainSoRefNumber, PrilCode, ExchangeRate,
			UpdateItemCode, updateListRawIndex, NetTotalValue, TaxCode,
			TaxRegNo,PrilCodeRet,MainDebCode;
	String deleteItemsValue, updatingItemsValue,DebtorPrilCode;
	// Main Calculation Variables
	int quantity = 0, totQuantity = 0, itemsDetDisFlag = 0, quantityValue = 0,
			freeQuantityValue = 0;
	int hedUpdate = 0;
	int calActive = 0;
	BigDecimal itemPrice = new BigDecimal("0.00");
	BigDecimal DisPer = new BigDecimal("0.00");
	BigDecimal preGrossAmount = new BigDecimal("0.00");
	BigDecimal preDiscountAmount = new BigDecimal("0.00");
	BigDecimal TaxComValue = new BigDecimal("0.00");
	BigDecimal taxPreAmount = new BigDecimal("0.00");
	BigDecimal GrossAmountWithTax = new BigDecimal("0.00");
	BigDecimal GrossAmountWithoutTax = new BigDecimal("0.00");
	BigDecimal ExchangeRateValue = new BigDecimal("0.00");
	BigDecimal ItemPriceValueExchange = new BigDecimal("0.00");
	BigDecimal ItemPriceValueExchangeTax = new BigDecimal("0.00");
	BigDecimal ItemPriceValueTax = new BigDecimal("0.00");
	BigDecimal ItemPriceValue = new BigDecimal("0.00");
	BigDecimal QtyValue = new BigDecimal("0.00");
	BigDecimal preDiscountAmountExchange = new BigDecimal("0.00");
	BigDecimal taxPreAmountExchange = new BigDecimal("0.00");
	BigDecimal GrossAmountWithoutTaxExchange = new BigDecimal("0.00");
	BigDecimal AmountValue = new BigDecimal("0.00");
	BigDecimal ExAmountValue = new BigDecimal("0.00");
	BigDecimal DisAmount = new BigDecimal("0.00");
	BigDecimal ExDisAmount = new BigDecimal("0.00");
	BigDecimal TaxAmount = new BigDecimal("0.00");
	BigDecimal ExTaxAmount = new BigDecimal("0.00");
	BigDecimal NetTotalValueAmt = new BigDecimal("0.00");
	BigDecimal NetTotalValueAmtUpdating = new BigDecimal("0.00");
	BigDecimal TotalTaxValFtaxDet = new BigDecimal("0.00");
	BigDecimal perHundred = new BigDecimal("100.00");
	// Current Item Original Price
	String ListPrice = "0.00";
	String RetailPrice = "0.00";
	int displayMode = 0;

	private TextView mCalculatorDisplay;
	private DM_BBM_CalculatorBrain mCalculatorBrain;
	DecimalFormat df = new DecimalFormat("@###########");
	// DecimalFormat formatValues = new DecimalFormat("#,###,##0.00");
	int delTag = 0;

	public void DisplayTaxListAction(View view) {
		TaxChangeItemCode = etbbmbbmproductcode.getText().toString();

		final Dialog dialog = new Dialog(
				DM_BBM_InvoiceSalesEditOrderDetails.this);
		dialog.setContentView(R.layout.dm_bbm_tax_dialog);
		dialog.setTitle("Tax Conbination");
		Button text = (Button) dialog.findViewById(R.id.btntitletext);

		TextView result1 = (TextView) dialog.findViewById(R.id.result1);
		TextView result2 = (TextView) dialog.findViewById(R.id.result2);
		TextView result4 = (TextView) dialog.findViewById(R.id.result4);
		TextView result5 = (TextView) dialog.findViewById(R.id.result5);
		TextView result7 = (TextView) dialog.findViewById(R.id.result7);
		TextView result8 = (TextView) dialog.findViewById(R.id.result8);
		TextView result10 = (TextView) dialog.findViewById(R.id.result10);
		TextView result11 = (TextView) dialog.findViewById(R.id.result11);

		Button result3 = (Button) dialog.findViewById(R.id.result3);
		Button result6 = (Button) dialog.findViewById(R.id.result6);
		Button result9 = (Button) dialog.findViewById(R.id.result9);
		Button result12 = (Button) dialog.findViewById(R.id.result12);

		text.setText("Select Tax From The List.");
		dialog.show();
		ListView lvtypedesftax = (ListView) findViewById(R.id.dmtaxlist);
		String[] fromtrdest = new String[] { "coldes_1", "coldes_2", "coldes_3" };
		int[] totrdest = new int[] { R.id.taxCode, R.id.taxRate,
				R.id.taxdetsummary };
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor taxList = null;
		try {
			// String querySelectDebtor =
			// "SELECT th.TaxComName,th.TaxComCode,td.TaxComCode,td.TaxCode,td.TaxRate FROM fTaxHed th,FtaxDet td WHERE th.TaxComCode = td.TaxComCode";
			String querySelectDebtor = "SELECT th.TaxComCode,th.TaxComName FROM fTaxHed th";
			taxList = mydb.rawQuery(querySelectDebtor, null);
		} catch (Exception e) {
		}

		if (taxList != null) {
			if (taxList.getCount() > 0) {
				int x = 0;
				while (taxList.moveToNext()) {
					x = x + 1;
					String record_0 = taxList.getString(0);// TaxCode
					String record_1 = taxList.getString(1);// TaxPer
					if (x == 1) {
						result1.setText(record_0);
						result2.setText(record_1);
						result3.setText(record_0 + "/" + record_1);
					} else if (x == 2) {
						result4.setText(record_0);
						result5.setText(record_1);
						result6.setText(record_0 + "/" + record_1);
					} else if (x == 3) {
						result7.setText(record_0);
						result8.setText(record_1);
						result9.setText(record_0 + "/" + record_1);
					} else if (x == 4) {
						result10.setText(record_0);
						result11.setText(record_1);
						result12.setText(record_0 + "/" + record_1);
					}

				}
			}
		}
		Button declineButton = (Button) dialog.findViewById(R.id.declineButton);
		// if decline button is clicked, close the custom dialog
		declineButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Close dialog
				dialog.dismiss();
			}
		});

		result3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Close dialog
				Button des = (Button) v;
				TaxChangeTaxCode = des.getText().toString();
				DisplayTaxDet();
				dialog.dismiss();
			}
		});

		result6.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Close dialog
				Button des = (Button) v;
				TaxChangeTaxCode = des.getText().toString();
				DisplayTaxDet();
				dialog.dismiss();
			}
		});

		result9.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Close dialog
				Button des = (Button) v;
				TaxChangeTaxCode = des.getText().toString();
				DisplayTaxDet();
				dialog.dismiss();
			}
		});

		result12.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Close dialog
				Button des = (Button) v;
				TaxChangeTaxCode = des.getText().toString();
				DisplayTaxDet();
				dialog.dismiss();
			}
		});

	}

	protected void DisplayTaxDet() {
		// TODO Auto-generated method stub
		String[] TaxChangeSum = TaxChangeTaxCode.split("/");
		String strTaxCode = TaxChangeSum[0].trim();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor taxDetList = null;
		try {
			// String querySelectDebtor =
			// "SELECT th.TaxComName,th.TaxComCode,td.TaxComCode,td.TaxCode,td.TaxRate FROM fTaxHed th,FtaxDet td WHERE th.TaxComCode = td.TaxComCode";
			String queryTaxDet = "SELECT TaxComCode,TaxRate,TaxCode FROM FtaxDet WHERE TaxComCode = '"
					+ strTaxCode + "'";
			taxDetList = mydb.rawQuery(queryTaxDet, null);
		} catch (Exception e) {
		}
		if (taxDetList != null) {
			if (taxDetList.getCount() > 0) {
				while (taxDetList.moveToNext()) {
					String strTaxComCode = taxDetList.getString(0);
					String strTaxRate = taxDetList.getString(1);
					TaxCode = taxDetList.getString(2);
					etbbmtaxcombination.setText(strTaxComCode);
					etbbmtaxvalue.setText(strTaxRate);
				}
			} else {
				etbbmtaxcombination.setText(strTaxCode);
				etbbmtaxvalue.setText("0.00");
			}
		} else {
			etbbmtaxcombination.setText(strTaxCode);
			etbbmtaxvalue.setText("0.00");
		}
	}

	// Display Items Details
	public void ShowItemsDetails(View view) {
		bbminvoiceitemslist.setVisibility(view.GONE);
		bbmsalesorditemdetail.setVisibility(view.VISIBLE);
		Button des = (Button) view;
		String currentItemCode = des.getText().toString();
		MainItemCode = currentItemCode.trim();
		// Check Item Currently Excisting
		displayMode = 100;
		checkSOItemExcisting();
	}

	public void btnItemsListBack(View view) {
		bbminvoiceitemslist.setVisibility(view.GONE);
		bbmsalesorditemdetail.setVisibility(view.VISIBLE);
	}

	private void checkSOItemExcisting() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor checkSoItems = null;
		try {
			String queryChkSalesOrder = "SELECT Itemcode FROM FOrdDet WHERE Itemcode = '"
					+ MainItemCode + "' AND RefNo = '" + MainSoRefNumber + "'";
			checkSoItems = mydb.rawQuery(queryChkSalesOrder, null);

		} catch (Exception e) {
		}
		if (checkSoItems != null) {
			if (checkSoItems.getCount() > 0) {
				while (checkSoItems.moveToNext()) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_BBM_InvoiceSalesEditOrderDetails.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("INVALID ITEM");
					// Setting Dialog Message
					alertDialog
							.setMessage("Selected Item Already Loaded. Please Select Another Item...");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				}
			} else {
				DisplayItemsDetils();
			}
		} else {
			DisplayItemsDetils();
		}

	}

	// Add new item
	public void onclickAddNewItem(View view) {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				DM_BBM_InvoiceSalesEditOrderDetails.this);

		if (etbbmquantity.getText().toString().trim().length() != 0) {
			String quantities = etbbmquantity.getText().toString();
			quantityValue = Integer.parseInt(quantities);
		}
		if (etbbmfreeqty.getText().toString().trim().length() != 0) {
			String freequantities = etbbmfreeqty.getText().toString();
			freeQuantityValue = Integer.parseInt(freequantities);
		}

		if (etbbmbbmproductcode.length() == 0) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_BBM_InvoiceSalesEditOrderDetails.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("INVALID SALES ORDER");
			// Setting Dialog Message
			alertDialog.setMessage("Please Add Sales Order Items");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		} else if (etbbmquantity.length() == 0 && etbbmfreeqty.length() == 0) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_BBM_InvoiceSalesEditOrderDetails.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("INVALID ITEMS QUANTITY");
			// Setting Dialog Message
			alertDialog.setMessage("Please Enter Items Quantity Details...");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

		else if (etbbmvalue.length() == 0 && etbbmfreeqty.length() == 0) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_BBM_InvoiceSalesEditOrderDetails.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("INVALID ITEMS");
			// Setting Dialog Message
			alertDialog.setMessage("Please Enter Items Quantity Details...");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		} else if (quantityValue <= 0 && freeQuantityValue <= 0) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_BBM_InvoiceSalesEditOrderDetails.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("INVALID ITEMS QUANTITY");
			// Setting Dialog Message
			alertDialog.setMessage("Items Quantity Should Not Be Zero...");
			// Setting Icon to Dialog
			// alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

		else {
			alertDialogBuilder.setTitle(this.getTitle());
			alertDialogBuilder.setMessage("Save Item Details");
			// set positive button: Yes message
			alertDialogBuilder.setPositiveButton("Yes",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							// go to a new activity of the app
							if (quantityValue > 0) {
								logSOStartTime();
								saveOrderTaxDetails();
								saveToSalesOrderDetails();
								clearFieldReset();
								resetTextBoxes();
								viewHeaderDetails();
							} else if (freeQuantityValue > 0) {
								logSOStartTime();
								saveOrderTaxDetails();
								saveToSalesOrderDetails();
								clearFieldReset();
								resetTextBoxes();
								viewHeaderDetails();
							}

							else {
								final AlertDialog alertDialog = new AlertDialog.Builder(
										DM_BBM_InvoiceSalesEditOrderDetails.this)
										.create();
								// Setting Dialog Title
								alertDialog.setTitle("INVALID ITEMS QUANTITY");
								// Setting Dialog Message
								alertDialog
										.setMessage("Items Quantity Should Not Be Zero...");
								// Setting Icon to Dialog
								// alertDialog.setIcon(R.drawable.warning);
								// Setting OK Button
								alertDialog.setButton("OK",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int which) {
												alertDialog.dismiss();
											}
										});
								// Showing Alert Message
								alertDialog.show();
								alertDialog.setCanceledOnTouchOutside(false);
								return;
							}

							dialog.cancel();
						}
					});
			// set negative button: No message
			alertDialogBuilder.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							// cancel the alert box and put a Toast to the user

							dialog.cancel();
						}
					});
			// set neutral button: Exit the app message
			alertDialogBuilder.setNeutralButton("Save/Exit",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							// exit the app and go to the HOME
							// go to a new activity of the app
							if (quantityValue > 0) {
								saveOrderTaxDetails();
								saveToSalesOrderDetails();

								Intent myIntent = new Intent(
										DM_BBM_InvoiceSalesEditOrderDetails.this,
										DM_BBM_InvoiceSalesOrder.class);
								// myIntent.putExtra("TAGID", "3");
								startActivity(myIntent);
							} else if (freeQuantityValue > 0) {
								saveOrderTaxDetails();
								saveToSalesOrderDetails();

								Intent myIntent = new Intent(
										DM_BBM_InvoiceSalesEditOrderDetails.this,
										DM_BBM_InvoiceSalesOrder.class);
								// myIntent.putExtra("TAGID", "3");
								startActivity(myIntent);
							}

							else {
								final AlertDialog alertDialog = new AlertDialog.Builder(
										DM_BBM_InvoiceSalesEditOrderDetails.this)
										.create();
								// Setting Dialog Title
								alertDialog.setTitle("INVALID ITEMS QUANTITY");
								// Setting Dialog Message
								alertDialog
										.setMessage("Items Quantity Should Not Be Zero...");
								// Setting Icon to Dialog
								// alertDialog.setIcon(R.drawable.warning);
								// Setting OK Button
								alertDialog.setButton("OK",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int which) {
												alertDialog.dismiss();
											}
										});
								// Showing Alert Message
								alertDialog.show();
								alertDialog.setCanceledOnTouchOutside(false);
								return;
							}
							dialog.cancel();
						}
					});

			AlertDialog alertDialog = alertDialogBuilder.create();
			// show alert
			alertDialog.show();
		}
	}

	protected void logSOStartTime() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curReadHeader = null;

		try {
			String querySelectOrdHeader = "SELECT RefNo,salesOrdStartTime FROM FOrdHed Where Active_State = '1'";
			curReadHeader = mydb.rawQuery(querySelectOrdHeader, null);

		} catch (Exception e) {
			Log.v(TAG, "Exception : " + e);
		}

		if (curReadHeader != null) {
			if (curReadHeader.getCount() > 0) {
				while (curReadHeader.moveToNext()) {
					String StartTimeRef = curReadHeader.getString(0);
					String StartTime = curReadHeader.getString(1);
					
					if (StartTime.equals("0")) {
						try {
							ContentValues add_SO_Hed_Update = new ContentValues();
							add_SO_Hed_Update.put("salesOrdStartTime",
									getAddDateTimeStringM().toString());
							mydb.update(FORDHED_TABLE, add_SO_Hed_Update,
									"RefNo ='" + StartTimeRef + "'", null);
						} catch (Exception e) {

						}
					}
				}
			}
		}
	}

	// Delete item
	public void onclickDeleteItem(View view) {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				DM_BBM_InvoiceSalesEditOrderDetails.this);

		alertDialogBuilder.setTitle(this.getTitle());
		alertDialogBuilder.setMessage("Delete Selected Item Details...");
		// set positive button: Yes message
		alertDialogBuilder.setPositiveButton("Yes",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// go to a new activity of the app
						delTag = 44;
						deleteCurrentItem();
						dialog.cancel();
					}
				});
		// set negative button: No message
		alertDialogBuilder.setNegativeButton("No",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// cancel the alert box and put a Toast to the user
						dialog.cancel();

					}
				});
		// set neutral button: Exit the app message
		alertDialogBuilder.setNeutralButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// exit the app and go to the HOME
						dialog.cancel();
					}
				});

		AlertDialog alertDialog = alertDialogBuilder.create();
		// show alert
		alertDialog.show();
	}

	protected void deleteCurrentItem() {
		// TODO Auto-generated method stub
		String ProductID = etbbmbbmproductcode.getText().toString().trim();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		try {
			mydb.delete(FORDDET_TABLE, "orddet_id ='" + updateListRawIndex
					+ "' AND Itemcode ='" + ProductID + "' AND RefNo ='"
					+ MainSoRefNumber + "'", null);
			deleteItemsValue = etbbmvalue.getText().toString();

			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
					DM_BBM_InvoiceSalesEditOrderDetails.this);
			alertDialogBuilder.setTitle("ITEM DELETE");
			alertDialogBuilder.setMessage("Selected Item Deleted Success..");
			// set positive button: Yes message
			alertDialogBuilder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							reArrageSequese();
							saveUpdateHeaderTotals();
							clearFieldReset();
							resetTextBoxes();
							viewHeaderDetails();
							dialog.cancel();
						}
					});
			// set negative button: No message
			alertDialogBuilder.setNegativeButton("OK/EXIT",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							// cancel the alert box and put a Toast to the user
							reArrageSequese();
							saveUpdateHeaderTotals();
							Intent myIntent = new Intent(getBaseContext(),
									DM_BBM_InvoiceSalesOrder.class);
							startActivityForResult(myIntent, 0);
							dialog.dismiss();
						}
					});
			AlertDialog alertDialog = alertDialogBuilder.create();
			// show alert
			alertDialog.show();

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}

		mydb.close();
		return;

	}

	// Update item
	public void onclickUpdateItem(View view) {
		if (etbbmquantity.getText().toString().trim().length() != 0) {
			String quantities = etbbmquantity.getText().toString();
			quantityValue = Integer.parseInt(quantities);
		}
		if (etbbmfreeqty.getText().toString().trim().length() != 0) {
			String freequantities = etbbmfreeqty.getText().toString();
			freeQuantityValue = Integer.parseInt(freequantities);
		}
		if (quantityValue <= 0 && freeQuantityValue <= 0) {

			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_BBM_InvoiceSalesEditOrderDetails.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("INVALID ITEMS QUANTITY");
			// Setting Dialog Message
			alertDialog.setMessage("Items Quantity Should Not Be Zero...");
			// Setting Icon to Dialog
			// alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		} else {
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
					DM_BBM_InvoiceSalesEditOrderDetails.this);
			alertDialogBuilder.setTitle(this.getTitle());
			alertDialogBuilder.setMessage("Update Selected Item Details...");
			// set positive button: Yes message
			alertDialogBuilder.setPositiveButton("Yes",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							// go to a new activity of the app
							if (quantityValue > 0 || freeQuantityValue > 0) {
								delTag = 66;
								saveOrderTaxDetails();
								UpdateToSalesOrderDetails();
								updatingItemsValue = etbbmvalue.getText()
										.toString();

								AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
										DM_BBM_InvoiceSalesEditOrderDetails.this);
								alertDialogBuilder.setTitle("ITEM UPDATE");
								alertDialogBuilder
										.setMessage("Selected Item Updated Success..");
								// set positive button: Yes message
								alertDialogBuilder.setPositiveButton("OK",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												reArrageSequese();
												saveUpdateHeaderTotals();
												clearFieldReset();
												resetTextBoxes();
												viewHeaderDetails();
												dialog.cancel();
											}
										});
								// set negative button: No message
								alertDialogBuilder.setNegativeButton("OK/EXIT",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												// cancel the alert box and put
												// a Toast to the user
												reArrageSequese();
												saveUpdateHeaderTotals();
												Intent myIntent = new Intent(
														getBaseContext(),
														DM_BBM_InvoiceSalesOrder.class);
												startActivityForResult(
														myIntent, 0);
												dialog.cancel();
											}
										});
								AlertDialog alertDialog = alertDialogBuilder
										.create();
								// show alert
								alertDialog.show();
							}

							else {
								final AlertDialog alertDialog = new AlertDialog.Builder(
										DM_BBM_InvoiceSalesEditOrderDetails.this)
										.create();
								// Setting Dialog Title
								alertDialog.setTitle("INVALID ITEMS QUANTITY");
								// Setting Dialog Message
								alertDialog
										.setMessage("Items Quantity Should Not Be Zero...");
								// Setting Icon to Dialog
								// alertDialog.setIcon(R.drawable.warning);
								// Setting OK Button
								alertDialog.setButton("OK",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int which) {
												alertDialog.dismiss();
											}
										});
								// Showing Alert Message
								alertDialog.show();
								alertDialog.setCanceledOnTouchOutside(false);
								return;
							}
						}
					});
			// set negative button: No message
			alertDialogBuilder.setNegativeButton("No",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							// cancel the alert box and put a Toast to the user
							dialog.cancel();

						}
					});
			// set neutral button: Exit the app message
			alertDialogBuilder.setNeutralButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							// exit the app and go to the HOME
							dialog.cancel();
						}
					});

			AlertDialog alertDialog = alertDialogBuilder.create();
			// show alert
			alertDialog.show();
		}
	}

	protected void UpdateToSalesOrderDetails() {
		// TODO Auto-generated method stub
		try {
			ContentValues Update_ord_det = new ContentValues();
			Update_ord_det.put("RefNo", MainSoRefNumber);
			Update_ord_det.put("TxnDate", getAddTaxnDate().toString());
			Update_ord_det.put("TxnType", "21");
			Update_ord_det.put("SeqNo", "1");
			Update_ord_det.put("Itemcode", etbbmbbmproductcode.getText()
					.toString());
			if (etbbmquantity.length() != 0) {
				Update_ord_det.put("Qty", etbbmquantity.getText().toString());
				Update_ord_det
						.put("BalQty", etbbmquantity.getText().toString());
			} else {
				Update_ord_det.put("Qty", "0");
				Update_ord_det.put("BalQty", "0");
			}
			Update_ord_det.put("TaxComCode", etbbmtaxcombination.getText()
					.toString());
			Update_ord_det.put("BSellPrice", etbbmsalesprice.getText()
					.toString());
			Update_ord_det.put("SellPrice", etbbmsalesprice.getText()
					.toString());

			String StrTaxValue = etbbmtaxvalue.getText().toString();

			BigDecimal TaxValueAmt = new BigDecimal(StrTaxValue.replaceAll("[,]", ""));
			String StrItemPrice = etbbmsalesprice.getText().toString();
			BigDecimal ItemPriceAmt = new BigDecimal(StrItemPrice.replaceAll("[,]", ""));

			BigDecimal ItemPriceAmtTax = ItemPriceAmt.add(ItemPriceAmt.multiply(TaxValueAmt)).divide(perHundred);
			ItemPriceAmtTax = ItemPriceAmtTax.setScale(2, BigDecimal.ROUND_HALF_DOWN);
			BigDecimal ItemValWithTax = ItemPriceAmt.add(ItemPriceAmtTax);

			Update_ord_det.put("BTSellPrice", "" + ItemValWithTax);
			Update_ord_det.put("TSellPrice", "" + ItemValWithTax);
			Update_ord_det.put("PrilCode", PrilCode);
			Update_ord_det.put("DisPer", etbbmbbmdiscount.getText().toString());
			Update_ord_det.put("BDisAmt", "" + preDiscountAmountExchange);
			Update_ord_det.put("DisAmt", etbbmbbmdiscountamount.getText()
					.toString());
			Update_ord_det.put("PDisAmt", etbbmbbmdiscountamount.getText()
					.toString());
			Update_ord_det.put("BPDisAmt", "" + preDiscountAmountExchange);
			Update_ord_det.put("BTaxAmt", "" + taxPreAmountExchange);
			Update_ord_det.put("TaxAmt", etbbmtaxamount.getText().toString());
			Update_ord_det.put("BAmt", etbbmvalue.getText().toString());
			Update_ord_det.put("Amt", etbbmvalue.getText().toString());
			Update_ord_det.put("Linkrec", "0");
			Update_ord_det.put("OrSellPrice", etbbmsalesprice.getText()
					.toString());
			Update_ord_det.put("OrBSellPrice", etbbmsalesprice.getText()
					.toString());
			Update_ord_det.put("OrTSellPrice", "0");
			Update_ord_det.put("OrBTSellPrice", "0");
			Update_ord_det.put("Packing", etbbmbbmpacking.getText().toString());
			Update_ord_det.put("Quopacking", "");
			Update_ord_det.put("cases", etbbmbbmcases.getText().toString());
			Update_ord_det.put("freeqty", etbbmfreeqty.getText().toString());
			Update_ord_det.put("balfreeqty", etbbmfreeqty.getText().toString());
			Update_ord_det.put("ItemName", etbbmbbmproductname.getText()
					.toString());
			Update_ord_det.put("RetailPrice", RetailPrice);
			Update_ord_det
					.put("BrandCode", etbbmbrandcode.getText().toString());
			Update_ord_det.put("BrandName", etbbmbrand.getText().toString());
			Update_ord_det.put("value", etbbmvalue.getText().toString());
			Update_ord_det.put("totordval", etbbmvalue.getText().toString());
			Update_ord_det.put("finalQty", etbbmfinalqty.getText().toString());
			Update_ord_det.put("itemTaxRate", etbbmtaxvalue.getText()
					.toString());
			mydb.update(FORDDET_TABLE, Update_ord_det, "orddet_id ='"
					+ updateListRawIndex + "' AND RefNo = '" + MainSoRefNumber
					+ "'", null);
			Log.v(TAG, "SO UPDAING :" + updateListRawIndex + "  REF :"
					+ MainSoRefNumber + "TAX :"
					+ etbbmtaxamount.getText().toString());
		} catch (Exception e) {
			Log.v(TAG, "SO Details Update Fail" + e);
		}
	}

	protected void saveToSalesOrderDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			Log.v(TAG, "***SAVE NEW ORD DET 99***" + MainSoRefNumber);
			ContentValues add_SO_Det = new ContentValues();
			add_SO_Det.put("RefNo", MainSoRefNumber);
			add_SO_Det.put("TxnDate", getAddTaxnDate().toString());
			add_SO_Det.put("TxnType", "21");
			add_SO_Det.put("SeqNo", "1");
			add_SO_Det
					.put("Itemcode", etbbmbbmproductcode.getText().toString());
			if (etbbmquantity.length() != 0) {
				add_SO_Det.put("Qty", etbbmquantity.getText().toString());
				add_SO_Det.put("BalQty", etbbmquantity.getText().toString());
			} else {
				add_SO_Det.put("Qty", "0");
				add_SO_Det.put("BalQty", "0");
			}
			add_SO_Det.put("TaxComCode", etbbmtaxcombination.getText()
					.toString());
			add_SO_Det.put("BSellPrice", etbbmsalesprice.getText().toString());
			add_SO_Det.put("SellPrice", etbbmsalesprice.getText().toString());

			String StrTaxValue = etbbmtaxvalue.getText().toString();

			BigDecimal TaxValueAmt = new BigDecimal(StrTaxValue.replaceAll("[,]", ""));
			String StrItemPrice = etbbmsalesprice.getText().toString();
			BigDecimal ItemPriceAmt = new BigDecimal(StrItemPrice.replaceAll("[,]", ""));

			BigDecimal ItemPriceAmtTax = ItemPriceAmt.add(ItemPriceAmt.multiply(TaxValueAmt)).divide(perHundred);
			ItemPriceAmtTax = ItemPriceAmtTax.setScale(2, BigDecimal.ROUND_HALF_DOWN);
			BigDecimal ItemValWithTax = ItemPriceAmt.add(ItemPriceAmtTax);

			add_SO_Det.put("BTSellPrice", "" + ItemValWithTax);
			add_SO_Det.put("TSellPrice", "" + ItemValWithTax);

			add_SO_Det.put("PrilCode", PrilCode);
			add_SO_Det.put("DisPer", etbbmbbmdiscount.getText().toString());
			add_SO_Det.put("BDisAmt", "" + preDiscountAmountExchange);
			add_SO_Det.put("DisAmt", etbbmbbmdiscountamount.getText()
					.toString());
			add_SO_Det.put("PDisAmt", etbbmbbmdiscountamount.getText()
					.toString());
			add_SO_Det.put("BPDisAmt", "" + preDiscountAmountExchange);
			add_SO_Det.put("BTaxAmt", "" + taxPreAmountExchange);
			add_SO_Det.put("TaxAmt", etbbmtaxamount.getText().toString());
			add_SO_Det.put("BAmt", etbbmvalue.getText().toString());
			add_SO_Det.put("Amt", etbbmvalue.getText().toString());
			add_SO_Det.put("Linkrec", "0");
			add_SO_Det.put("OrSellPrice", etbbmsalesprice.getText().toString());
			add_SO_Det
					.put("OrBSellPrice", etbbmsalesprice.getText().toString());
			add_SO_Det.put("OrTSellPrice", "0");
			add_SO_Det.put("OrBTSellPrice", "0");
			add_SO_Det.put("Packing", etbbmbbmpacking.getText().toString());
			add_SO_Det.put("Quopacking", "");
			if (etbbmbbmcases.length() != 0) {
				add_SO_Det.put("cases", etbbmbbmcases.getText().toString());
			} else {
				add_SO_Det.put("cases", "0");
			}
			if (etbbmfreeqty.length() != 0) {
				add_SO_Det.put("freeqty", etbbmfreeqty.getText().toString());
				add_SO_Det.put("balfreeqty", etbbmfreeqty.getText().toString());
			} else {
				add_SO_Det.put("freeqty", "0");
				add_SO_Det.put("balfreeqty", "0");
			}

			add_SO_Det
					.put("ItemName", etbbmbbmproductname.getText().toString());
			add_SO_Det.put("RetailPrice", RetailPrice);
			add_SO_Det.put("BrandCode", etbbmbrandcode.getText().toString());
			add_SO_Det.put("BrandName", etbbmbrand.getText().toString());
			add_SO_Det.put("value", etbbmvalue.getText().toString());
			add_SO_Det.put("totordval", etbbmvalue.getText().toString());
			add_SO_Det.put("finalQty", etbbmfinalqty.getText().toString());
			add_SO_Det.put("syncDet", "0");
			add_SO_Det.put("itemoriSalePrice", ListPrice);
			add_SO_Det.put("itemTaxRate", etbbmtaxvalue.getText().toString());

			Log.v(TAG, "ListPrice :" + ListPrice + "=="
					+ etbbmsalesprice.getText().toString());
			mydb.insert(FORDDET_TABLE, null, add_SO_Det);
			mydb.close();
		} catch (Exception e) {
			Log.v(TAG, "SO Details Insert Fail" + e);
		}
		// Calculating Current Total And Update

		reArrageSequese();
		saveUpdateHeaderTotals();
	}

	private void saveOrderTaxDetails() {
		// TODO Auto-generated method stub
		Log.v(TAG, "***saveOrderTaxDetails***" + MainSoRefNumber + "="
				+ TaxCode);
		String CurrentItemCode = etbbmbbmproductcode.getText().toString();
		String CurrentTaxCode = etbbmtaxcombination.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curChkTaxCode = null;
		String queryChkTaxCode;
		try {
			queryChkTaxCode = "SELECT * from FOrdTaxDt Where RefNo = '"
					+ MainSoRefNumber + "' AND ItemCode = '" + CurrentItemCode
					+ "'";
			curChkTaxCode = mydb.rawQuery(queryChkTaxCode, null);
		} catch (Exception e) {
			Log.v(TAG, "Save Order Tax Details Exception:" + e);
		}

		if (curChkTaxCode != null) {
			if (curChkTaxCode.getCount() > 0) {
				while (curChkTaxCode.moveToNext()) {
					Log.v(TAG, "Tax Record Excisting...");
					ContentValues updateOrdTaxDt = new ContentValues();
					String TaxDetRecordId = curChkTaxCode.getString(0);
					String Taxseq = curChkTaxCode.getString(7);
					String TaxDetAmt = curChkTaxCode.getString(9);

					updateOrdTaxDt.put("RefNo", MainSoRefNumber);
					updateOrdTaxDt.put("ItemCode", etbbmbbmproductcode
							.getText().toString());
					updateOrdTaxDt.put("TaxComCode", etbbmtaxcombination
							.getText().toString());
					updateOrdTaxDt.put("TaxCode", TaxCode);
					updateOrdTaxDt.put("TaxPer", etbbmtaxvalue.getText()
							.toString());
					updateOrdTaxDt.put("TaxRate", etbbmtaxvalue.getText()
							.toString());
					updateOrdTaxDt.put("Taxseq", "1");
					updateOrdTaxDt.put("BTaxDetAmt", etbbmtaxamount.getText()
							.toString());
					updateOrdTaxDt.put("TaxDetAmt", etbbmtaxamount.getText()
							.toString());

					mydb.update(FORDTAXDT_TABLE, updateOrdTaxDt,
							"taxdet_id = '" + TaxDetRecordId + "'", null);
				}
			} else {

				Log.v(TAG, "***ADD NEW saveOrderTaxDetails***");
				ContentValues add_Tax_Det = new ContentValues();
				add_Tax_Det.put("RefNo", MainSoRefNumber);
				add_Tax_Det.put("ItemCode", etbbmbbmproductcode.getText()
						.toString());
				add_Tax_Det.put("TaxComCode", etbbmtaxcombination.getText()
						.toString());
				add_Tax_Det.put("TaxCode", TaxCode);
				add_Tax_Det.put("TaxPer", etbbmtaxvalue.getText().toString());
				add_Tax_Det.put("TaxRate", etbbmtaxvalue.getText().toString());
				add_Tax_Det.put("Taxseq", "1");
				add_Tax_Det.put("BTaxDetAmt", etbbmtaxamount.getText()
						.toString());
				add_Tax_Det.put("TaxDetAmt", etbbmtaxamount.getText()
						.toString());

				mydb.insert(FORDTAXDT_TABLE, null, add_Tax_Det);
				// mydb.close();
			}
		} else {
			Log.v(TAG, "Tax Record NULL...");
		}
		/*********************************************************/
		// private String FORDTAXRG_TABLE = "FOrdTaxRg";
		// RefNo ,TaxCode ,TaxRegNo

		Cursor curChkTaxReg = null;
		String queryChkTaxReg;
		try {
			queryChkTaxReg = "SELECT RefNo,TaxCode from FOrdTaxRg Where RefNo = '"
					+ MainSoRefNumber + "' AND TaxCode = '" + TaxCode + "'";
			curChkTaxReg = mydb.rawQuery(queryChkTaxReg, null);
		} catch (Exception e) {
			Log.v(TAG, "Save Order Tax Details Exception:" + e);
		}
		if (curChkTaxReg != null) {
			if (curChkTaxReg.getCount() > 0) {
				while (curChkTaxReg.moveToNext()) {

				}
			} else {
				Log.v(TAG, "***ADD NEW save FOrdTaxRg***");
				ContentValues add_Tax_Reg = new ContentValues();
				add_Tax_Reg.put("RefNo", MainSoRefNumber);
				add_Tax_Reg.put("TaxCode", TaxCode);
				add_Tax_Reg.put("TaxRegNo", DebtorTaxRegNo);
				mydb.insert(FORDTAXRG_TABLE, null, add_Tax_Reg);
				mydb.close();
			}
		}
	}

	private void reArrageSequese() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curItemsDetailsValueSeq = null;
		String queryItemsDetailsSeq;
		try {
			queryItemsDetailsSeq = "SELECT orddet_id,SeqNo,RefNo from FOrdDet Where RefNo = '"
					+ MainSoRefNumber + "'";
			curItemsDetailsValueSeq = mydb.rawQuery(queryItemsDetailsSeq, null);
		} catch (Exception e) {
			Log.v(TAG, "Exception :" + e);
		}
		if (curItemsDetailsValueSeq != null) {
			if (curItemsDetailsValueSeq.getCount() > 0) {
				int SeqNoValue = 0;
				while (curItemsDetailsValueSeq.moveToNext()) {
					SeqNoValue = SeqNoValue + 1;
					String StrIndex = curItemsDetailsValueSeq.getString(0);
					ContentValues updateSeq = new ContentValues();
					updateSeq.put("SeqNo", "" + SeqNoValue);
					mydb.update(FORDDET_TABLE, updateSeq, "RefNo ='"
							+ MainSoRefNumber + "' AND orddet_id ='" + StrIndex
							+ "'", null);
				}
			}
		}
		curItemsDetailsValueSeq.close();
		mydb.close();
	}

	/******** Calculating Current Total And Update ********/
	private void saveUpdateHeaderTotals() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curItemsDetailsValue = null;
		String queryItemsDetails;
		try {
			queryItemsDetails = "SELECT Amt,BAmt,DisAmt,BDisAmt,TaxAmt,BTaxAmt,RefNo,totordval from FOrdDet Where RefNo = '"
					+ MainSoRefNumber + "'";
			curItemsDetailsValue = mydb.rawQuery(queryItemsDetails, null);
		} catch (Exception e) {
			Log.v(TAG, "Exception :" + e);
		}
		if (curItemsDetailsValue != null) {
			if (curItemsDetailsValue.getCount() > 0) {
				while (curItemsDetailsValue.moveToNext()) {
					String StrAmt = curItemsDetailsValue.getString(0);
					String StrBAmt = curItemsDetailsValue.getString(1);
					String StrDisAmt = curItemsDetailsValue.getString(2);
					String StrBDisAmt = curItemsDetailsValue.getString(3);
					String StrTaxAmt = curItemsDetailsValue.getString(4);
					String StrBTaxAmt = curItemsDetailsValue.getString(5);
					String totordval = curItemsDetailsValue.getString(7);

					Log.v(TAG, "StrAmt *****1 :" + StrAmt);
					Log.v(TAG, "StrBAmt ****2 :" + StrBAmt);
					Log.v(TAG, "StrDisAmt **3 :" + StrDisAmt);
					Log.v(TAG, "StrBDisAmt *4 :" + StrBDisAmt);
					Log.v(TAG, "StrTaxAmt **5 :" + StrTaxAmt);
					Log.v(TAG, "StrBTaxAmt *6 :" + StrBTaxAmt);
					Log.v(TAG, "totordval **7 :" + totordval);

					try {
						// Amount
						if (StrAmt != null) {
							BigDecimal StrAmtVal = new BigDecimal(
									StrAmt.replaceAll("[,]", ""));
							AmountValue = AmountValue.add(StrAmtVal);
						}
						// Amount With Exchange
						if (StrBAmt != null) {
							BigDecimal StrBAmtVal = new BigDecimal(
									StrBAmt.replaceAll("[,]", ""));
							ExAmountValue = ExAmountValue.add(StrBAmtVal);
						}
						// Discount
						if (StrDisAmt != null) {
							BigDecimal StrStrDisAmt = new BigDecimal(
									StrDisAmt.replaceAll("[,]", ""));
							DisAmount = DisAmount.add(StrStrDisAmt);
						}
						// Discount With Exchange
						if (StrBDisAmt != null) {
							BigDecimal StrBDisAmtVal = new BigDecimal(
									StrBDisAmt.replaceAll("[,]", ""));
							ExDisAmount = ExDisAmount.add(StrBDisAmtVal);
						}
						// Tax
						if (StrTaxAmt != null) {
							BigDecimal StrTaxAmtVal = new BigDecimal(
									StrTaxAmt.replaceAll("[,]", ""));
							TaxAmount = TaxAmount.add(StrTaxAmtVal);
						}
						// Tax With Exchange
						if (StrBTaxAmt != null) {
							BigDecimal StrBTaxAmtVal = new BigDecimal(
									StrBTaxAmt.replaceAll("[,]", ""));
							ExTaxAmount = ExTaxAmount.add(StrBTaxAmtVal);
						}
						if (totordval != null) {
							BigDecimal Strtotordval = new BigDecimal(
									totordval.replaceAll("[,]", ""));
							NetTotalValueAmt = new BigDecimal(
									NetTotalValue.replaceAll("[,]", ""));

							if (delTag == 44) {
								BigDecimal delItemsTotValue = new BigDecimal(
										deleteItemsValue.replaceAll("[,]", ""));
								NetTotalValueAmt = NetTotalValueAmt
										.divide(delItemsTotValue);

							} else if (delTag == 66) {
								BigDecimal updateItemsTotValue = new BigDecimal(
										updatingItemsValue
												.replaceAll("[,]", ""));
								NetTotalValueAmt = NetTotalValueAmtUpdating
										.add(updateItemsTotValue);
							} else {
								Log.v(TAG, "SAVE  :" + NetTotalValueAmt + "+"
										+ Strtotordval);
								NetTotalValueAmt = NetTotalValueAmt
										.add(Strtotordval);

							}
						}
					} catch (Exception e) {

					}

				}
			} else {
				hedUpdate = 404;
			}
		}

		/******* Update Final Values ***************/
		AmountValue = AmountValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
		ExAmountValue = ExAmountValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
		DisAmount = DisAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN);
		ExDisAmount = ExDisAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN);
		TaxAmount = TaxAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN);
		ExTaxAmount = ExTaxAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN);
		NetTotalValueAmt = NetTotalValueAmt.setScale(2,
				BigDecimal.ROUND_HALF_DOWN);

		if (hedUpdate == 404) {
			try {
				ContentValues add_SO_Hed_Update = new ContentValues();
				add_SO_Hed_Update.put("TotalAmt", "0.00");
				add_SO_Hed_Update.put("BTotalAmt", "0.00");
				add_SO_Hed_Update.put("TotalDis", "0.00");
				add_SO_Hed_Update.put("PTotalDis", "0.00");
				add_SO_Hed_Update.put("BTotalDis", "0.00");
				add_SO_Hed_Update.put("BPTotalDis", "0.00");
				add_SO_Hed_Update.put("TotalTax", "0.00");
				add_SO_Hed_Update.put("BTotalTax", "0.00");
				add_SO_Hed_Update.put("InvHedNetTotal", "0.00");
				mydb.update(FORDHED_TABLE, add_SO_Hed_Update, "RefNo ='"
						+ MainSoRefNumber + "'", null);
			} catch (Exception e) {

			}
		} else {
			try {
				Log.v(TAG, "TotalAmt/BTotalAmt****3 :" + NetTotalValueAmt + "=" + ExAmountValue);
				ContentValues add_SO_Hed_Update = new ContentValues();
				add_SO_Hed_Update.put("TotalAmt", "" + NetTotalValueAmt);
				add_SO_Hed_Update.put("BTotalAmt", "" + ExAmountValue);
				add_SO_Hed_Update.put("TotalDis", "" + DisAmount);
				add_SO_Hed_Update.put("PTotalDis", "" + DisAmount);
				add_SO_Hed_Update.put("BTotalDis", "" + ExDisAmount);
				add_SO_Hed_Update.put("BPTotalDis", "" + ExDisAmount);
				add_SO_Hed_Update.put("TotalTax", "" + TaxAmount);
				add_SO_Hed_Update.put("BTotalTax", "" + ExTaxAmount);
				add_SO_Hed_Update.put("InvHedNetTotal", "" + NetTotalValueAmt);

				mydb.update(FORDHED_TABLE, add_SO_Hed_Update, "RefNo ='"
						+ MainSoRefNumber + "'", null);
			} catch (Exception e) {

			}
		}
		mydb.close();
	}

	private void DisplayItemsDetils() {
		// TODO Auto-generated method stub
		Log.v(TAG, "MainItemCode :" + MainItemCode);
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curItemsDetails = null;
		Cursor curBrandDetails = null;
		Cursor curFreeQtyDetails = null;
		Cursor curListPrice = null;
		Cursor curTaxCombination = null;
		Cursor curdebtorDetails= null;
		try {
			String querySelectDebtor = "SELECT DebCode,PrilCode FROM fDebtor Where DebCode = '"
					+ MainDebCode + "'";
			curdebtorDetails = mydb.rawQuery(querySelectDebtor, null);

		} catch (Exception e) {
			Log.v(TAG, "Exception :" + e);
		}
		if (curdebtorDetails != null) {
			if (curdebtorDetails.getCount() > 0) {
				while (curdebtorDetails.moveToNext()) {
					DebtorPrilCode = curdebtorDetails.getString(1);
					Log.v(TAG, "DebtorPrilCode 24062014:" + DebtorPrilCode);
				}
			}
		}
		
		
		
		String ItemCode, ItemName, BrandCode, AvgPrice, packing, BrandName = null, FreeQty = null, TaxComCode, TaxComRateValue = null;
		try {
			String querySelectItemsDet = "SELECT ItemCode,ItemName,BrandCode,AvgPrice,PrilCode,packing,PackSize,TaxComCode FROM FItems Where ItemCode = '"
					+ MainItemCode + "'";
			curItemsDetails = mydb.rawQuery(querySelectItemsDet, null);

		} catch (Exception e) {
			Log.v(TAG, "Exception :" + e);
		}

		Log.v(TAG, "ITEM COUNT :" + curItemsDetails.getCount());
		if (curItemsDetails != null) {
			if (curItemsDetails.getCount() > 0) {
				while (curItemsDetails.moveToNext()) {
					ItemCode = curItemsDetails.getString(0);
					ItemName = curItemsDetails.getString(1);
					BrandCode = curItemsDetails.getString(2);
					AvgPrice = curItemsDetails.getString(3);
					// PrilCode = curItemsDetails.getString(4);
					PrilCode = "WHOLE SALE";
					PrilCodeRet = "RETAIL";
					packing = curItemsDetails.getString(5);
					PackSize = curItemsDetails.getString(6);
					TaxComCode = curItemsDetails.getString(7);
					Log.v(TAG, "ItemCode :" + ItemCode + "/BrandCode="
							+ BrandCode);
					try {
						String querySelectBrand = "SELECT BrandCode,BrandName FROM FBrand Where BrandCode = '"
								+ BrandCode + "'";
						curBrandDetails = mydb.rawQuery(querySelectBrand, null);

					} catch (Exception e) {
					}
					if (curBrandDetails != null) {
						if (curBrandDetails.getCount() > 0) {
							while (curBrandDetails.moveToNext()) {
								BrandCode = curBrandDetails.getString(0);
								BrandName = curBrandDetails.getString(1);
								Log.v(TAG, "ITEM :" + BrandCode + "-"
										+ BrandName);
							}
						} else {
							Log.v(TAG, "ITEM COUNT Brand = 0");
						}
					}

					try {
						String queryFreeQty = "SELECT ItemCode,FreeQty FROM fItemFreeQty Where ItemCode = '"
								+ MainItemCode + "'";
						curFreeQtyDetails = mydb.rawQuery(queryFreeQty, null);

					} catch (Exception e) {
					}
					if (curFreeQtyDetails != null) {
						if (curFreeQtyDetails.getCount() > 0) {
							while (curFreeQtyDetails.moveToNext()) {
								FreeQty = curFreeQtyDetails.getString(1);
							}
						} else {
							Log.v(TAG, "ITEM COUNT FreeQty = 0");
							FreeQty = "0";
						}
					}

					try {
						String queryListPrice = "SELECT Price,PrilCode FROM fItemPri Where ItemCode ='"
								+ MainItemCode
								+ "'";
						curListPrice = mydb.rawQuery(queryListPrice, null);

					} catch (Exception e) {
					}
					if (curListPrice != null) {
						if (curListPrice.getCount() > 0) {
							while (curListPrice.moveToNext()) {
								
								String currentPLCode = curListPrice.getString(1);
								Log.v(TAG, "PLCODE 24062014:" + DebtorPrilCode + "=" + currentPLCode);
								if(DebtorPrilCode.equals("WHOLE SALE")){
									if(currentPLCode.equals("WHOLE SALE")){
										ListPrice = curListPrice.getString(0);
									}
									else if(currentPLCode.equals("RETAIL")){
										RetailPrice = curListPrice.getString(0);
									}
									else{
										ListPrice = curListPrice.getString(0);
									}
								}
								else if(currentPLCode.equals("RETAIL")){
									if(currentPLCode.equals("RETAIL")){
										ListPrice = curListPrice.getString(0);
										RetailPrice = curListPrice.getString(0);
									}
									else{
										ListPrice = curListPrice.getString(0);
										RetailPrice = curListPrice.getString(0);
									}
								}
							}
						} else {
							ListPrice = "1.00";
							RetailPrice = "1.00";
						}
					}
					Log.v(TAG, "ITEM ListPrice : " + ListPrice);
					Log.v(TAG, "********************################********************(0)" + ListPrice);
					try {
						String queryTaxVal = "SELECT td.TaxComCode,td.TaxRate,td.TaxCode,tx.TaxCode,tx.TaxName,tx.TaxRegNo FROM FtaxDet td,fTax tx Where td.TaxCode = tx.TaxCode AND TaxComCode = '"
								+ TaxComCode + "'";
						curTaxCombination = mydb.rawQuery(queryTaxVal, null);

					} catch (Exception e) {
					}

					if (curTaxCombination != null) {
						if (curTaxCombination.getCount() > 0) {
							while (curTaxCombination.moveToNext()) {
								TaxComRateValue = curTaxCombination.getString(1);
								TaxCode = curTaxCombination.getString(2);
								TaxRegNo = curTaxCombination.getString(5);
							}
						} else {
							TaxComRateValue = "0.00";
						}
					}
					etbbmsalesprice.setText(ListPrice);
					Log.v(TAG, "********************################********************(1)" + ListPrice);
					etbbmbbmpacksize.setText(PackSize);
					etbbmbbmproductcode.setText(ItemCode);
					etbbmbbmproductname.setText(ItemName);
					etbbmbbmpacking.setText(packing);
					etbbmbrandcode.setText(BrandCode);
					etbbmbrand.setText(BrandName);
					etbbmfinalqty.setText(FreeQty);
					if (itemsDetDisFlag != 99) {
						etbbmsalesprice.setText(ListPrice);
						Log.v(TAG, "********************################********************(2)" + ListPrice);
					}

					if (displayMode == 100) {
						etbbmtaxcombination.setText(TaxComCode);
						etbbmtaxvalue.setText(TaxComRateValue);
					} else if (displayMode == 200) {

					}

				}
			} else {
				Log.v(TAG, "ITEM COUNT 0");
			}
		}
		curItemsDetails.close();
		curBrandDetails.close();
		curItemsDetails.close();
		mydb.close();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_invoice_sales_order_details);
		Log.v(TAG, "DM_BBM_InvoiceSalesEditOrderDetails");
		// get the action bar
		ActionBar actionBar = getActionBar();
		actionBar = getActionBar();
		// Hide the action bar title
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(false);

		dbHelperCustomerItems = new DM_BBM_List_Adapters(this);
		dbHelperCustomerItems.open();

		// Button Controllers
		etbbmbbmproductcode = (Button) findViewById(R.id.etbbmbbmproductcode);
		btndeletetransaction = (Button) findViewById(R.id.btndeletetransaction);
		btnprinttransaction = (Button) findViewById(R.id.btnprinttransaction);
		btnundotransaction = (Button) findViewById(R.id.btnundotransaction);

		// LinearLayout Parent View Controllers
		bbminvoiceitemslist = (LinearLayout) findViewById(R.id.bbminvoiceitemslist);
		bbmsalesorditemdetail = (LinearLayout) findViewById(R.id.bbmsalesorditemdetail);

		// EditText box Read only components
		etbbmbbmproductname = (EditText) findViewById(R.id.etbbmbbmproductname);
		etbbmbbmpacking = (EditText) findViewById(R.id.etbbmbbmpacking);
		etbbmbrand = (EditText) findViewById(R.id.etbbmbrand);
		etbbmbrandcode = (EditText) findViewById(R.id.etbbmbrandcode);
		etbbmfinalqty = (EditText) findViewById(R.id.etbbmfinalqty);
		etbbmsalesprice = (EditText) findViewById(R.id.etbbmsalesprice);
		etbbmtaxcombination = (Button) findViewById(R.id.etbbmtaxcombination);
		etbbmbbmdiscount = (EditText) findViewById(R.id.etbbmbbmdiscount);
		etbbmbbmpacksize = (EditText) findViewById(R.id.etbbmbbmpacksize);
		etbbmbbmcases = (EditText) findViewById(R.id.etbbmbbmcases);
		etbbmquantity = (EditText) findViewById(R.id.etbbmquantity);
		etbbmfreeqty = (EditText) findViewById(R.id.etbbmfreeqty);
		etbbmvalue = (EditText) findViewById(R.id.etbbmvalue);
		etbbmtaxvalue = (EditText) findViewById(R.id.etbbmtaxvalue);

		etbbmbbmdiscountamount = (EditText) findViewById(R.id.etbbmbbmdiscountamount);
		etbbmtaxamount = (EditText) findViewById(R.id.etbbmtaxamount);
		etbbmamountwouttax = (EditText) findViewById(R.id.etbbmamountwouttax);
		etbbmamountwithtax = (EditText) findViewById(R.id.etbbmamountwithtax);

		myFilterCustomerItems = (EditText) findViewById(R.id.dminvfiltercustomeritems);

		etbbmbbmproductcode.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				bbminvoiceitemslist.setVisibility(view.VISIBLE);
				bbmsalesorditemdetail.setVisibility(view.GONE);
			}

		});
		getLoadItemsDetails();
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			btndeletetransaction.setEnabled(true);
			UpdateItemCode = extras.getString("TAGID");
			MainSoRefNumber = extras.getString("TAGIDREF");
			MainItemCode = UpdateItemCode.trim();

			Log.v(TAG, "EDIT ItemCode**********:" + UpdateItemCode);
			Log.v(TAG, "EDIT MainItemCode******:" + MainItemCode);
			if (MainItemCode.equals("0")) {
				btnprinttransaction.setEnabled(false);
				btnundotransaction.setEnabled(false);
				itemsDetDisFlag = 0;
				viewHeaderDetails();
			} else {
				btndeletetransaction.setEnabled(false);
				viewHeaderDetails();
				DisplayItemsDetils();
				viewCurrentItemsDetails();
			}

		}

		etbbmsalesprice.addTextChangedListener(filterPriceTextChangeWatcher);
		etbbmquantity.addTextChangedListener(filterQuantityTextChangeWatcher);
		etbbmbbmcases.addTextChangedListener(filterCasesTextChangeWatcher);
		etbbmtaxvalue.addTextChangedListener(filterTaxValueTextChangeWatcher);
	}

	private void viewCurrentItemsDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curViewItemsDetails = null;
		String queryViewItemsDetails;

		try {
			queryViewItemsDetails = "SELECT od.orddet_id,od.Itemcode,od.ItemName,od.BrandName,od.Packing,od.cases,od.Qty,od.freeqty,od.SellPrice,od.DisPer,od.TaxComCode,od.DisAmt,od.TaxAmt,od.Amt,oh.RefNo,oh.CurRate,od.value,od.totordval,od.RefNo,od.itemTaxRate,od.RetailPrice,od.itemoriSalePrice FROM FOrdHed oh ,FOrdDet od Where oh.RefNo = od.RefNo AND oh.RefNo = '"
					+ MainSoRefNumber
					+ "' AND od.Itemcode = '"
					+ UpdateItemCode + "'";
			curViewItemsDetails = mydb.rawQuery(queryViewItemsDetails, null);
		} catch (Exception e) {

		}
		if (curViewItemsDetails != null) {
			if (curViewItemsDetails.getCount() > 0) {
				while (curViewItemsDetails.moveToNext()) {

					updateListRawIndex = curViewItemsDetails.getString(0);
					Log.v(TAG, "updateListRawIndex****1  :"
							+ updateListRawIndex);
					/*
					 * String Itemcode = curViewItemsDetails.getString(1);
					 * String ItemName = curViewItemsDetails.getString(2);
					 * String BrandName = curViewItemsDetails.getString(3);
					 * String Packing = curViewItemsDetails.getString(4);
					 */
					String cases = curViewItemsDetails.getString(5);
					String Qty = curViewItemsDetails.getString(6);
					String freeqty = curViewItemsDetails.getString(7);
					String SellPrice = curViewItemsDetails.getString(8);
					String DisAmt = curViewItemsDetails.getString(11);
					String TaxAmt = curViewItemsDetails.getString(12);
					String Amt = curViewItemsDetails.getString(13);
					String value = curViewItemsDetails.getString(16);
					String totordvalue = curViewItemsDetails.getString(17);
					String taxCode = curViewItemsDetails.getString(10);
					String taxRate = curViewItemsDetails.getString(19);
					RetailPrice = curViewItemsDetails.getString(20);
					ListPrice = curViewItemsDetails.getString(21);
					// Current Net Total Value
					BigDecimal currentItemTotVal = new BigDecimal(
							totordvalue.replaceAll("[,]", ""));
					// Taking this value as total value on update modifications
					NetTotalValueAmt = new BigDecimal(NetTotalValue.replaceAll(
							"[,]", ""));
					NetTotalValueAmtUpdating = NetTotalValueAmt
							.subtract(currentItemTotVal);
					Log.v(TAG, "READ CURRENT VALUE  :" + NetTotalValueAmt + "-"
							+ currentItemTotVal);

					etbbmbbmcases.setText(cases);
					etbbmquantity.setText(Qty);
					etbbmfreeqty.setText(freeqty);
					etbbmsalesprice.setText(SellPrice);
					Log.v(TAG, "********************################********************(3)" + SellPrice);
					etbbmvalue.setText(value);
					etbbmbbmdiscountamount.setText(DisAmt);
					etbbmtaxamount.setText(TaxAmt);
					etbbmamountwouttax.setText(Amt);
					// etbbmamountwithtax.setText(totordvalue);
				}
			}
		}

	}

	private void viewHeaderDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curReadHeader = null;

		try {
			String querySelectOrdHeader = "SELECT * FROM FOrdHed Where Active_State = '33'";
			curReadHeader = mydb.rawQuery(querySelectOrdHeader, null);

		} catch (Exception e) {
			Log.v(TAG, "Exception : " + e);
		}
		if (curReadHeader != null) {
			if (curReadHeader.getCount() > 0) {
				while (curReadHeader.moveToNext()) {
					MainSoRefNumber = curReadHeader.getString(1);
					ExchangeRate = curReadHeader.getString(7);
					MainDebCode = curReadHeader.getString(8);
					DebtorTaxRegNo = curReadHeader.getString(22);
					String DisPer = curReadHeader.getString(32);
					NetTotalValue = curReadHeader.getString(45);

					etbbmbbmdiscount.setText(DisPer);
					etbbmamountwithtax.setText(NetTotalValue);
					Log.v(TAG, "MainSoRefNumber : " + MainSoRefNumber);
					Log.v(TAG, "ExchangeRateval : " + ExchangeRate);
					Log.v(TAG, "DisPer : " + DisPer);
					Log.v(TAG, "NetTotalValue : " + NetTotalValue);

				}
			}
		} else {
			Log.v(TAG, "Exception  vvvvv : ");
		}

	}

	private void getLoadItemsDetails() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*******populateCustomerDetailsList*******");
		Cursor cursor = dbHelperCustomerItems.fetchAllItems();

		// The desired columns to be bound
		String[] columns = new String[] { DM_BBM_List_Adapters.KEY_ITEMCODE,
				DM_BBM_List_Adapters.KEY_ITEMNAME,
				DM_BBM_List_Adapters.KEY_BRAND,
				DM_BBM_List_Adapters.KEY_PACKSIZE,
				DM_BBM_List_Adapters.KEY_FREEQTY,
				DM_BBM_List_Adapters.KEY_ITEMCODE };
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2", "coldes_3",
				"coldes_4", "coldes_5" , "coldes_6" };
		// the XML defined views which the data will be bound to
		int[] to = new int[] { R.id.grid_value_a, R.id.grid_value_b,
				R.id.grid_value_c, R.id.grid_value_d, R.id.grid_value_e, R.id.rawindexitemcode };

		// create the adapter using the cursor pointing to the desired data
		// as well as the layout information
		dataAdapterCusomerItems = new SimpleCursorAdapter(this,
				R.layout.dm_bbm_items_list_raw, cursor, columns, to, 0);

		ListView listView = (ListView) findViewById(R.id.listviewItems);
		// Assign adapter to ListView
		listView.setAdapter(dataAdapterCusomerItems);

		myFilterCustomerItems.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				dataAdapterCusomerItems.getFilter().filter(s.toString());
			}
		});

		dataAdapterCusomerItems
				.setFilterQueryProvider(new FilterQueryProvider() {
					public Cursor runQuery(CharSequence constraint) {
						return dbHelperCustomerItems
								.fetchAllItemsByName(constraint.toString());
					}
				});

	}

	private String getAddDateTimeStringM() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	/******************* Text Change Event Handler (CASES) ****************/
	private TextWatcher filterCasesTextChangeWatcher = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			int packSize = 0, noOfCases = 0, totQuantity = 0;
			Log.v(TAG, "afterTextChanged (1)");
			if (etbbmbbmpacksize.length() != 0) {
				String packSizeStr = etbbmbbmpacksize.getText().toString();
				packSize = Integer.parseInt(packSizeStr);
				if (etbbmbbmcases.length() != 0) {
					String noOfCasesStr = etbbmbbmcases.getText().toString();
					noOfCases = Integer.parseInt(noOfCasesStr);
					totQuantity = packSize * noOfCases;
					String totQuantityStr = Integer.toString(totQuantity);
					etbbmquantity.setText(totQuantityStr);
				} else {
					Log.v(TAG, "Empty Values");
					etbbmquantity.setText("");

				}
			}

		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			Log.v(TAG, "beforeTextChanged (2)");
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			Log.v(TAG, "onTextChanged (3)");
		}

	};

	/******************* Text Change Event Handler (QUANTITY) ****************/

	private TextWatcher filterQuantityTextChangeWatcher = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			Log.v(TAG, "afterTextChanged (1)");
			if (etbbmquantity.length() != 0 && etbbmsalesprice.length() != 0) {
				ExchangeRateValue = new BigDecimal(ExchangeRate.replaceAll(
						"[,]", ""));
				String StrTaxComValue = etbbmtaxvalue.getText().toString();
				TaxComValue = new BigDecimal(StrTaxComValue.replaceAll("[,]",
						""));

				TaxComValue = TaxComValue.divide(perHundred);

				String StrQty = etbbmquantity.getText().toString();
				String StrItemPrice = etbbmsalesprice.getText().toString();

				BigDecimal QtyValue = new BigDecimal(StrQty.replaceAll("[,]",
						""));
				BigDecimal ItemPriceValue = new BigDecimal(
						StrItemPrice.replaceAll("[,]", ""));

				preGrossAmount = QtyValue.multiply(ItemPriceValue);

				// Check Discount Percentage Value
				if (etbbmbbmdiscount.length() != 0) {
					// Calculate Discount Amount With Discount Percentage
					String StrDisPer = etbbmbbmdiscount.getText().toString();
					DisPer = new BigDecimal(StrDisPer.replaceAll("[,]", ""));

					DisPer = DisPer.divide(perHundred);
					preDiscountAmount = preGrossAmount.multiply(DisPer);

					// Calculate Tax Amount With Discount Percentage
					taxPreAmount = (preGrossAmount.subtract(preDiscountAmount))
							.multiply(TaxComValue);
				}
				// Calculate Without Discount Percentage
				else {
					taxPreAmount = preGrossAmount.multiply(TaxComValue);
				}
			} else {
				clearFieldReset();
			}

			/**** Calculation With Exchange Rate Value *****/
			// BSellPrice Value
			ItemPriceValueExchange = ItemPriceValue.multiply(ExchangeRateValue);
			// BTSellPrice Value
			ItemPriceValueExchangeTax = ItemPriceValueExchange.multiply(TaxComValue);
			// TSellPrice Value
			ItemPriceValueTax = ItemPriceValue.multiply(TaxComValue);

			/**********************************************/

			GrossAmountWithoutTax = (preGrossAmount.subtract(preDiscountAmount));
			GrossAmountWithTax = (preGrossAmount.subtract(preDiscountAmount))
					.add(taxPreAmount);

			// Rounding BigDecimal values
			preGrossAmount = preGrossAmount.setScale(2,
					BigDecimal.ROUND_HALF_DOWN);
			preDiscountAmount = preDiscountAmount.setScale(2,
					BigDecimal.ROUND_HALF_DOWN);
			taxPreAmount = taxPreAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN);
			GrossAmountWithoutTax = GrossAmountWithoutTax.setScale(2,
					BigDecimal.ROUND_HALF_DOWN);
			GrossAmountWithTax = GrossAmountWithTax.setScale(2,
					BigDecimal.ROUND_HALF_DOWN);

			/**** Calculation With Exchange Rate Value *****/
			// BDisAmt Value
			preDiscountAmountExchange = preDiscountAmount
					.multiply(ExchangeRateValue);
			// BTaxAmt Value
			taxPreAmountExchange = taxPreAmount.multiply(ExchangeRateValue);
			// BAmt Value
			GrossAmountWithoutTaxExchange = GrossAmountWithoutTax
					.multiply(ExchangeRateValue);
			/**********************************************/

			// Print Values
			// BigDecimal.toString(preGrossAmount)
			preGrossAmount = preGrossAmount.setScale(2,
					BigDecimal.ROUND_HALF_DOWN);
			String PrintPreGrossAmount = "" + preGrossAmount;
			// BigDecimal.toString(preDiscountAmount)
			preDiscountAmount = preDiscountAmount.setScale(2,
					BigDecimal.ROUND_HALF_DOWN);
			String printDiscountAmt = "" + preDiscountAmount;
			// BigDecimal.toString(taxPreAmount)
			taxPreAmount = taxPreAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN);
			String printTaxPreAmount = "" + taxPreAmount;
			// BigDecimal.toString(GrossAmountWithoutTax)
			GrossAmountWithoutTax = GrossAmountWithoutTax.setScale(2,
					BigDecimal.ROUND_HALF_DOWN);
			String printAmountWithoutTax = "" + GrossAmountWithoutTax;
			// BigDecimal.toString(GrossAmountWithTax)
			BigDecimal GrossAmount = GrossAmountWithTax
					.subtract(preDiscountAmount);
			GrossAmount = GrossAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN);

			String printAmountWithTax = "" + GrossAmount;
			BigDecimal NetValue = (GrossAmountWithTax
					.subtract(preDiscountAmount)).add(taxPreAmount);
			NetValue = NetValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
			String printNetValue = "" + NetValue;

			etbbmvalue.setText(printNetValue);
			etbbmbbmdiscountamount.setText(printDiscountAmt);
			etbbmtaxamount.setText(printTaxPreAmount);
			etbbmamountwouttax.setText(printAmountWithoutTax);

			if (itemsDetDisFlag == 0) {
				// Print Net Total Value For the Sales Order
				BigDecimal currentTotNetValue = new BigDecimal(
						NetTotalValue.replaceAll("[,]", ""));
				currentTotNetValue = currentTotNetValue.add(NetValue);
				currentTotNetValue = currentTotNetValue.setScale(2,
						BigDecimal.ROUND_HALF_DOWN);
				etbbmamountwithtax.setText("" + currentTotNetValue);
			} else if (itemsDetDisFlag == 99) {
				// Print Net Total Value For the Sales Order
				BigDecimal currentTotNetValue = new BigDecimal(""
						+ NetTotalValueAmtUpdating);
				currentTotNetValue = currentTotNetValue.add(NetValue);
				currentTotNetValue = currentTotNetValue.setScale(2,
						BigDecimal.ROUND_HALF_DOWN);
				etbbmamountwithtax.setText("" + currentTotNetValue);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			Log.v(TAG, "beforeTextChanged (2)");
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			Log.v(TAG, "onTextChanged (3)");
		}

	};

	/******* Text Change Events Complete ********/

	/******************* Text Change Event Handler (PRICE) ****************/
	private TextWatcher filterPriceTextChangeWatcher = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			Log.v(TAG, "afterTextChanged (1)");
			if (etbbmquantity.length() != 0 && etbbmsalesprice.length() != 0) {

				// ExchangeRateValue =
				// BigDecimal.parseBigDecimal(ExchangeRate.replaceAll(
				// "[,]", ""));
				ExchangeRateValue = new BigDecimal("1.00");
				String StrTaxComValue = etbbmtaxvalue.getText().toString();
				TaxComValue = new BigDecimal(StrTaxComValue.replaceAll("[,]",
						""));
				TaxComValue = TaxComValue.divide(perHundred);

				String StrQty = etbbmquantity.getText().toString();
				String StrItemPrice = etbbmsalesprice.getText().toString();

				BigDecimal QtyValue = new BigDecimal(StrQty.replaceAll("[,]",
						""));
				BigDecimal ItemPriceValue = new BigDecimal(
						StrItemPrice.replaceAll("[,]", ""));

				preGrossAmount = QtyValue.multiply(ItemPriceValue);

				// Check Discount Percentage Value
				if (etbbmbbmdiscount.length() != 0) {
					// Calculate Discount Amount With Discount Percentage
					String StrDisPer = etbbmbbmdiscount.getText().toString();
					DisPer = new BigDecimal(StrDisPer.replaceAll("[,]", ""));
					DisPer = DisPer.divide(perHundred);
					preDiscountAmount = preGrossAmount.multiply(DisPer);

					// Calculate Tax Amount With Discount Percentage
					taxPreAmount = (preGrossAmount.subtract(preDiscountAmount))
							.multiply(TaxComValue);
				}
				// Calculate Without Discount Percentage
				else {
					taxPreAmount = preGrossAmount.multiply(TaxComValue);
				}
			} else {
				clearFieldReset();
			}

			/**** Calculation With Exchange Rate Value *****/
			// BSellPrice Value
			ItemPriceValueExchange = ItemPriceValue.multiply(ExchangeRateValue);
			// BTSellPrice Value
			ItemPriceValueExchangeTax = ItemPriceValueExchange.multiply(TaxComValue);
			// TSellPrice Value
			ItemPriceValueTax = ItemPriceValue.multiply(TaxComValue);

			/**********************************************/

			GrossAmountWithoutTax = (preGrossAmount.subtract(preDiscountAmount));
			GrossAmountWithTax = ((preGrossAmount.subtract(preDiscountAmount))
					.add(taxPreAmount));

			// Rounding BigDecimal values
			preGrossAmount = preGrossAmount.setScale(2,
					BigDecimal.ROUND_HALF_DOWN);
			preDiscountAmount = preDiscountAmount.setScale(2,
					BigDecimal.ROUND_HALF_DOWN);
			taxPreAmount = taxPreAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN);
			GrossAmountWithoutTax = GrossAmountWithoutTax.setScale(2,
					BigDecimal.ROUND_HALF_DOWN);
			GrossAmountWithTax = GrossAmountWithTax.setScale(2,
					BigDecimal.ROUND_HALF_DOWN);

			/**** Calculation With Exchange Rate Value *****/
			// BDisAmt Value
			preDiscountAmountExchange = preDiscountAmount
					.multiply(ExchangeRateValue);
			// BTaxAmt Value
			taxPreAmountExchange = taxPreAmount.multiply(ExchangeRateValue);
			// BAmt Value
			GrossAmountWithoutTaxExchange = GrossAmountWithoutTax
					.multiply(ExchangeRateValue);
			/**********************************************/

			// Print Values
			// BigDecimal.toString(preGrossAmount)
			String PrintPreGrossAmount = "" + preGrossAmount;
			// BigDecimal.toString(preDiscountAmount)
			String printDiscountAmt = "" + preDiscountAmount;
			// BigDecimal.toString(taxPreAmount)
			String printTaxPreAmount = "" + taxPreAmount;
			// BigDecimal.toString(GrossAmountWithoutTax)
			String printAmountWithoutTax = "" + GrossAmountWithoutTax;
			// BigDecimal.toString(GrossAmountWithTax)
			BigDecimal GrossAmount = GrossAmountWithTax
					.subtract(preDiscountAmount);
			String printAmountWithTax = "" + GrossAmount;

			BigDecimal NetValue = ((preGrossAmount.subtract(preDiscountAmount))
					.add(taxPreAmount));

			String printNetValue = "" + NetValue;

			etbbmvalue.setText(printNetValue);
			etbbmbbmdiscountamount.setText(printDiscountAmt);
			etbbmtaxamount.setText(printTaxPreAmount);
			etbbmamountwouttax.setText(printAmountWithoutTax);

			if (itemsDetDisFlag == 0) {
				// Print Net Total Value For the Sales Order
				BigDecimal currentTotNetValue = new BigDecimal(
						NetTotalValue.replaceAll("[,]", ""));
				currentTotNetValue = currentTotNetValue.add(NetValue);
				currentTotNetValue = currentTotNetValue.setScale(2,
						BigDecimal.ROUND_HALF_DOWN);
				etbbmamountwithtax.setText("" + currentTotNetValue);
			} else if (itemsDetDisFlag == 99) {
				// Print Net Total Value For the Sales Order
				BigDecimal currentTotNetValue = NetTotalValueAmtUpdating;
				currentTotNetValue = currentTotNetValue.add(NetValue);
				currentTotNetValue = currentTotNetValue.setScale(2,
						BigDecimal.ROUND_HALF_DOWN);
				etbbmamountwithtax.setText("" + currentTotNetValue);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			Log.v(TAG, "beforeTextChanged (2)");
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			Log.v(TAG, "onTextChanged (3)");
		}

	};

	/******************* Text Change Event Handler (QUANTITY) ****************/
	private TextWatcher filterTaxValueTextChangeWatcher = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			Log.v(TAG, "afterTextChanged (1)");
			if (etbbmquantity.length() != 0 && etbbmsalesprice.length() != 0) {
				Log.v(TAG, "ExchangeRateval DET: " + ExchangeRate);
				try {
					ExchangeRateValue = new BigDecimal(ExchangeRate.replaceAll(
							"[,]", ""));
				} catch (Exception e) {
					ExchangeRateValue = new BigDecimal("1.00");
				}

				String StrTaxComValue = etbbmtaxvalue.getText().toString();
				TaxComValue = new BigDecimal(StrTaxComValue.replaceAll("[,]",
						""));

				TaxComValue = TaxComValue.divide(perHundred);

				String StrQty = etbbmquantity.getText().toString();
				String StrItemPrice = etbbmsalesprice.getText().toString();

				QtyValue = new BigDecimal(StrQty.replaceAll("[,]", ""));
				ItemPriceValue = new BigDecimal(StrItemPrice.replaceAll("[,]",
						""));

				preGrossAmount = QtyValue.multiply(ItemPriceValue);

				// Check Discount Percentage Value
				if (etbbmbbmdiscount.length() != 0) {
					// Calculate Discount Amount With Discount Percentage
					String StrDisPer = etbbmbbmdiscount.getText().toString();
					DisPer = new BigDecimal(StrDisPer.replaceAll("[,]", ""));
					DisPer = DisPer.divide(perHundred);

					preDiscountAmount = preGrossAmount.multiply(DisPer);

					// Calculate Tax Amount With Discount Percentage
					taxPreAmount = preGrossAmount.subtract(preDiscountAmount);
					taxPreAmount = taxPreAmount.multiply(TaxComValue);
				}
				// Calculate Without Discount Percentage
				else {
					taxPreAmount = preGrossAmount.multiply(TaxComValue);
				}
			} else {
				clearFieldReset();
			}

			/**** Calculation With Exchange Rate Value *****/
			// BSellPrice Value
			ItemPriceValueExchange = ItemPriceValue.multiply(ExchangeRateValue);
			// BTSellPrice Value
			ItemPriceValueExchangeTax = ItemPriceValueExchange
					.multiply(TaxComValue);
			// TSellPrice Value
			ItemPriceValueTax = ItemPriceValue.multiply(TaxComValue);

			/**********************************************/

			GrossAmountWithoutTax = (preGrossAmount.subtract(preDiscountAmount));
			GrossAmountWithTax = preGrossAmount.subtract(preDiscountAmount);
			GrossAmountWithTax = GrossAmountWithTax.add(taxPreAmount);
			// Rounding BigDecimal values

			preGrossAmount = preGrossAmount.setScale(2,
					BigDecimal.ROUND_HALF_DOWN);
			preDiscountAmount = preDiscountAmount.setScale(2,
					BigDecimal.ROUND_HALF_DOWN);
			taxPreAmount = taxPreAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN);
			GrossAmountWithoutTax = GrossAmountWithoutTax.setScale(2,
					BigDecimal.ROUND_HALF_DOWN);
			GrossAmountWithTax = GrossAmountWithTax.setScale(2,
					BigDecimal.ROUND_HALF_DOWN);

			/**** Calculation With Exchange Rate Value *****/
			// BDisAmt Value
			preDiscountAmountExchange = preDiscountAmount
					.multiply(ExchangeRateValue);
			// BTaxAmt Value
			taxPreAmountExchange = taxPreAmount.multiply(ExchangeRateValue);
			// BAmt Value
			GrossAmountWithoutTaxExchange = GrossAmountWithoutTax
					.multiply(ExchangeRateValue);
			/**********************************************/

			// Print Values
			// BigDecimal.toString(preGrossAmount)
			String PrintPreGrossAmount = "" + preGrossAmount;
			// BigDecimal.toString(preDiscountAmount)
			String printDiscountAmt = "" + preDiscountAmount;
			// BigDecimal.toString(taxPreAmount)
			String printTaxPreAmount = "" + taxPreAmount;
			// BigDecimal.toString(GrossAmountWithoutTax)
			String printAmountWithoutTax = "" + GrossAmountWithoutTax;
			// BigDecimal.toString(GrossAmountWithTax)

			BigDecimal GrossAmount = GrossAmountWithTax
					.subtract(preDiscountAmount);

			String printAmountWithTax = "" + GrossAmount;

			BigDecimal NetValue = preGrossAmount.subtract(preDiscountAmount);
			NetValue = NetValue.add(taxPreAmount);

			String printNetValue = "" + NetValue;

			etbbmvalue.setText(printNetValue);
			etbbmbbmdiscountamount.setText(printDiscountAmt);
			etbbmtaxamount.setText(printTaxPreAmount);
			etbbmamountwouttax.setText(printAmountWithoutTax);

			if (itemsDetDisFlag == 0) {
				// Print Net Total Value For the Sales Order
				BigDecimal currentTotNetValue = new BigDecimal(
						NetTotalValue.replaceAll("[,]", ""));

				currentTotNetValue = currentTotNetValue.add(NetValue);
				currentTotNetValue = currentTotNetValue.setScale(2,
						BigDecimal.ROUND_HALF_DOWN);
				etbbmamountwithtax.setText("" + currentTotNetValue);
			} else if (itemsDetDisFlag == 99) {
				// Print Net Total Value For the Sales Order
				BigDecimal currentTotNetValue = new BigDecimal(""
						+ NetTotalValueAmtUpdating);
				currentTotNetValue = currentTotNetValue.add(NetValue);
				currentTotNetValue = currentTotNetValue.setScale(2,
						BigDecimal.ROUND_HALF_DOWN);
				etbbmamountwithtax.setText("" + currentTotNetValue);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			Log.v(TAG, "beforeTextChanged (2)");
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			Log.v(TAG, "onTextChanged (3)");
		}

	};

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

	protected void clearFieldReset() {
		// TODO Auto-generated method stub
		quantity = 0;
		totQuantity = 0;
		itemPrice = new BigDecimal("0.00");
		DisPer = new BigDecimal("0.00");
		preGrossAmount = new BigDecimal("0.00");
		preDiscountAmount = new BigDecimal("0.00");
		TaxComValue = new BigDecimal("0.00");
		taxPreAmount = new BigDecimal("0.00");
		GrossAmountWithTax = new BigDecimal("0.00");
		GrossAmountWithoutTax = new BigDecimal("0.00");
		ExchangeRateValue = new BigDecimal("0.00");
		ItemPriceValueExchange = new BigDecimal("0.00");
		ItemPriceValueExchangeTax = new BigDecimal("0.00");
		ItemPriceValueTax = new BigDecimal("0.00");
		ItemPriceValue = new BigDecimal("0.00");
		QtyValue = new BigDecimal("0.00");
		preDiscountAmountExchange = new BigDecimal("0.00");
		taxPreAmountExchange = new BigDecimal("0.00");
		GrossAmountWithoutTaxExchange = new BigDecimal("0.00");
		AmountValue = new BigDecimal("0.00");
		ExAmountValue = new BigDecimal("0.00");
		DisAmount = new BigDecimal("0.00");
		ExDisAmount = new BigDecimal("0.00");
		TaxAmount = new BigDecimal("0.00");
		ExTaxAmount = new BigDecimal("0.00");
		NetTotalValueAmt = new BigDecimal("0.00");
		TotalTaxValFtaxDet = new BigDecimal("0.00");

		etbbmvalue.setText("0.00");
		etbbmbbmdiscountamount.setText("0.00");
		etbbmtaxamount.setText("0.00");
		etbbmamountwouttax.setText("0.00");
		// etbbmamountwithtax.setText("0.00");
	}

	protected void resetTextBoxes() {
		// TODO Auto-generated method stub
		etbbmbbmproductcode.setText("");
		etbbmbbmproductname.setText("");
		etbbmbrand.setText("");
		etbbmbbmpacking.setText("");
		etbbmfinalqty.setText("");
		etbbmbbmpacksize.setText("");
		etbbmbbmcases.setText("");
		etbbmquantity.setText("");
		etbbmfreeqty.setText("");
		etbbmsalesprice.setText("");
		etbbmbbmdiscount.setText("0.00");
		etbbmvalue.setText("");
		etbbmtaxcombination.setText("");
		etbbmtaxvalue.setText("");
		etbbmbbmdiscountamount.setText("");
		etbbmtaxamount.setText("");
		etbbmamountwouttax.setText("");
	}

	private String getAddTaxnDate() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("dd-MM-yyyy");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	/************ Action Bar Activities ****************/
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			LocationFound();
			return true;
		case R.id.action_refresh:
			// refresh
			calActive = 200;
			LaunchCalculator();
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void LaunchCalculator() {
		// TODO Auto-generated method stub
		final Dialog dialog = new Dialog(
				DM_BBM_InvoiceSalesEditOrderDetails.this);
		dialog.setContentView(R.layout.dm_bbm_calculator);
		dialog.setTitle("Calculator");

		mCalculatorBrain = new DM_BBM_CalculatorBrain();
		mCalculatorDisplay = (TextView) dialog.findViewById(R.id.textView1);

		DM_BBM_CusListener buttonListener = new DM_BBM_CusListener(
				mCalculatorDisplay, mCalculatorBrain);

		df.setMinimumFractionDigits(0);
		df.setMinimumIntegerDigits(1);
		df.setMaximumIntegerDigits(8);

		dialog.findViewById(R.id.button0).setOnClickListener(buttonListener);
		dialog.findViewById(R.id.button1).setOnClickListener(buttonListener);
		dialog.findViewById(R.id.button2).setOnClickListener(buttonListener);
		dialog.findViewById(R.id.button3).setOnClickListener(buttonListener);
		dialog.findViewById(R.id.button4).setOnClickListener(buttonListener);
		dialog.findViewById(R.id.button5).setOnClickListener(buttonListener);
		dialog.findViewById(R.id.button6).setOnClickListener(buttonListener);
		dialog.findViewById(R.id.button7).setOnClickListener(buttonListener);
		dialog.findViewById(R.id.button8).setOnClickListener(buttonListener);
		dialog.findViewById(R.id.button9).setOnClickListener(buttonListener);

		dialog.findViewById(R.id.buttonAdd).setOnClickListener(buttonListener);
		dialog.findViewById(R.id.buttonSubtract).setOnClickListener(
				buttonListener);
		dialog.findViewById(R.id.buttonMultiply).setOnClickListener(
				buttonListener);
		dialog.findViewById(R.id.buttonDivide).setOnClickListener(
				buttonListener);
		dialog.findViewById(R.id.buttonToggleSign).setOnClickListener(
				buttonListener);
		dialog.findViewById(R.id.buttonDecimalPoint).setOnClickListener(
				buttonListener);
		dialog.findViewById(R.id.buttonEquals).setOnClickListener(
				buttonListener);
		dialog.findViewById(R.id.buttonClear)
				.setOnClickListener(buttonListener);
		dialog.findViewById(R.id.buttonClearMemory).setOnClickListener(
				buttonListener);
		dialog.findViewById(R.id.buttonAddToMemory).setOnClickListener(
				buttonListener);
		dialog.findViewById(R.id.buttonSubtractFromMemory).setOnClickListener(
				buttonListener);
		dialog.findViewById(R.id.buttonRecallMemory).setOnClickListener(
				buttonListener);

		Button dialogButton = (Button) dialog.findViewById(R.id.close_btn);

		dialogButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		dialog.show();
	}

	private void LocationFound() {
		// TODO Auto-generated method stub
		Intent i = new Intent(DM_BBM_InvoiceSalesEditOrderDetails.this,
				DM_BBM_InvoiceSalesOrder.class);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(i);
		finish();
		return;
	}

	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// Save variables on screen orientation change
		if (calActive == 200) {
			outState.putDouble("OPERAND", mCalculatorBrain.getResult());
			outState.putDouble("MEMORY", mCalculatorBrain.getMemory());
		}
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		// Restore variables on screen orientation change
		mCalculatorBrain.setOperand(savedInstanceState.getDouble("OPERAND"));
		mCalculatorBrain.setMemory(savedInstanceState.getDouble("MEMORY"));
		mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
	}

}
